<script setup>
import {
  Edit, Delete, Position, Upload
} from '@element-plus/icons-vue'
import {

} from '@/api/allApi.js'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getallbookservice, getpartpathservice,
  updatepathservice, detailbookservice, deletepathservice, lendbookservice, getallbookcategoryservice
} from '@/api/book.js'
import { getPayPhasesservice, deletef3service } from '@/api/allApi.js'
import {
  addinputservice, getpartclientservice,getcontractsservice,getinputsservice,getresetpricesservice,
  getAllUserForClientComeAddservice, updateoughttimecomeservice,deleteinputservice
} from '@/api/client.js'
//控制添加分类弹窗
const dialogVisible = ref(false)
const lenddialogVisible = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
//const pageSize = ref(3)//每页条数
//文章分类数据模型
const clients = ref([])
const users = ref([])
const contracts = ref([])
const userdepartment = ref(null)
//用户搜索时选中的分类id
const bookcategorylist = async () => {
  let result = await getpartclientservice({
    pageNum: 1,
    pageSize: 1000,
    str: ''
  });
  clients.value = result.data.items;
  console.log(clients.value);

}
bookcategorylist();
const listuser = async () => {
  let result = await getAllUserForClientComeAddservice();

  users.value = result.data;
  console.log(result);
}
listuser();
//定义变量，控制标题
const title = ref('')
//与后端交互的json数据
const pathmodel = ref({
  id: null,
  contractid: null,
  inputprice: null,
  paytime: null,
  userid: null,
  comment: null
})
const sheets = ref([{}, {}])
const findmodel = ref({
  pageNum: 1,
  pageSize: 5,
  str: ''
})
const getcontracts = async () => {
  let result = await getcontractsservice({
  pageNum: 1,
  pageSize: 1000,
  str: ''
});
  contracts.value = result.data.items;
};
getcontracts();

const f3list = async () => {
  console.log(findmodel.value);
  let result = await getinputsservice(findmodel.value);
  console.log(result.items);
  total.value = result.data.total;
  sheets.value = result.data.items;
}
f3list();
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  findmodel.value.pageSize = size;
  f3list();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  findmodel.value.pageNum = num;
  f3list();
}
const cleardata = () => {
  findmodel.value.str = ''
}
//表单校验
const rules = {
  contractid: [
    { required: true, message: '请选择合同', trigger: 'blur' },
  ],
  comment: [
    { required: true, message: '请输入备注', trigger: 'blur' },
  ],
  
  paytime: [
    { required: true, message: '请选择到账时间', trigger: 'blur' },
  ],
  inputprice: [
    { required: true, message: '请输入到款金额', trigger: 'blur' },
    {
            validator: (rule, value, callback) => {
                if (value < 0) {
                    callback(new Error('金额不能为负数'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
  ],
}
const add = () => {
  for (let key in pathmodel.value) {
    if (pathmodel.value.hasOwnProperty(key)) {
      pathmodel.value[key] = null;
    }
  }
  dialogVisible.value = true;
  title.value = '添加应收帐'
}
const formref = ref(null); //表单校验
const addpath = async () => {
  console.log(pathmodel.value);
  formref.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('信息填写不完整！');
    }
    else {
      console.log(pathmodel.value);
      let result = await addinputservice(pathmodel.value);
      if (result.code == 0) {
        ElMessage.success("添加成功")
        dialogVisible.value = false;
        f3list();
      }
      else {
        ElMessage.error(result.message ? result.message : '添加失败')
      }
    }
  });
}
const updatepath = async () => {
  console.log(pathmodel.value);
  pathmodel.value.contract = null
  formref.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('信息填写不完整！');
    }
    else {
      console.log(pathmodel.value);
      let result = await updateoughttimecomeservice(pathmodel.value);
      if (result.code == 0) {
        ElMessage.success("修改成功")
        dialogVisible.value = false;
        f3list();
      }
      else {
        ElMessage.error(result.message ? result.message : '修改失败')
      }
    }
  });
}
//删除分类
const del = (row) => {
  ElMessageBox.confirm(
    '你确认删除该条信息吗？',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      //用户点击了确认
      let result = await deleteinputservice(row.id)
      if (result.code == 0) {
        ElMessage.success('删除成功')
        f3list();
      }
      else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      //用户点击了取消
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//展示编辑弹窗
const showDialog = (row) => {
  title.value = '修改应收帐';
  dialogVisible.value = true;
  //数据拷贝
  Object.keys(row).forEach((key) => {
    pathmodel.value[key] = row[key];
  });
  console.log(row);

  const user = users.value.find(user => user.id === row.userid);
  userdepartment.value = user.department
  pathmodel.value.department = user.department
}

const handleContractChange =async (id) => {
  console.log(id);
  const contract = contracts.value.find(contract => contract.id === id) ?
    contracts.value.find(contract => contract.id === id) : null;
  if (contract != null) {
    pathmodel.value.name = contract.name
    pathmodel.value.clientcompanyname = contract.quote.chance.clientCompany.clientcompanyname
    pathmodel.value.allprices = contract.quote.allprices
    pathmodel.value.clientcompanyid = contract.quote.chance.clientCompany.id
    let result = await getresetpricesservice(id)
    pathmodel.value.resetprices = result.data
  } else {
    pathmodel.value.name = null
    pathmodel.value.clientcompanyname = null
    pathmodel.value.allprices = null
    pathmodel.value.clientcompanyid = null
    pathmodel.value.resetprices = null
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>应收帐录入</span>
        <div class="extra">
          <el-button type="primary" @click="add">新增录入</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="查询条件：">
        <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="f3list">搜索</el-button>
        <el-button @click="cleardata">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="sheets" style="width: 100%">
      <el-table-column label="序号" type="index" width="60"> </el-table-column>
      <el-table-column label="合同号" prop="contractid"> </el-table-column>
      <el-table-column label="合同名称" prop="contract.name"> </el-table-column>
      <el-table-column label="收款金额" prop="inputprice"> </el-table-column>
      <el-table-column label="收款时间" prop="paytime"> </el-table-column>
      <el-table-column label="收款人" prop="user.name"> </el-table-column>
      <el-table-column label="操作" width="60">
        <template #default="{ row }">
          <!-- <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button> -->
          <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
      :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background :total="total"
      @size-change="onSizeChange" @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end" />
  </el-card>
  <!-- 添加分类弹窗 -->
  <el-dialog v-model="dialogVisible" :title="title" width="40%">
    <el-form :model="pathmodel" ref="formref" :rules="rules" label-width="100px" style="padding-right: 30px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同号" prop="contractid">
            <el-select placeholder="请选择..." clearable style="width: 300px" @change="handleContractChange"
              v-model="pathmodel.contractid">
              <el-option v-for="c in contracts" :key="c.id" :label="c.id" :value="c.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同名称" prop="name">
            <el-input v-model="pathmodel.name" disabled style="width: 300px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="clientcompanyname">
            <el-input v-model="pathmodel.clientcompanyname" disabled style="width: 300px"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同总额" prop="allprices">
            <el-input v-model="pathmodel.allprices" disabled style="width: 300px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="公司编号" prop="clientcompanyid">
            <el-input v-model="pathmodel.clientcompanyid" disabled style="width: 300px"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="剩余金额" prop="resetprices">
            <el-input v-model="pathmodel.resetprices" disabled style="width: 300px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="到款时间" prop="paytime">
            <el-date-picker v-model="pathmodel.paytime" style="width: 350px" type="date"
                            placeholder="请选择..." format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到款金额" prop="inputprice">
            <el-input v-model="pathmodel.inputprice" type="number" style="width: 300px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="comment">
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="pathmodel.comment"
                ></el-input>
              </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addpath"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>